<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="群分享码" prop="groupCode">
        <el-input
            v-model="queryParams.groupCode"
            placeholder="请输入分享码"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="群名称" prop="groupName">
        <el-input
            v-model="queryParams.groupName"
            placeholder="请输入群名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="时间">
        <el-col :span="15">
          <el-date-picker
              v-model="queryParams.findTime"
              type="daterange"
              @change="handleQuery"
              range-separator="To"
              start-placeholder="Start date"
              end-placeholder="End date"
          />
        </el-col>
      </el-form-item>
      <!--
      <el-form-item label="打水次数" prop="competitionNum">
        <el-input
          v-model="queryParams.competitionNum"
          placeholder="请输入打水次数"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="活动次数" prop="activityNum">
        <el-input
          v-model="queryParams.activityNum"
          placeholder="请输入活动次数"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="固定男生收费" prop="fixedMale">
        <el-input
          v-model="queryParams.fixedMale"
          placeholder="请输入固定男生收费"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="固定女生收费" prop="fixedFemale">
        <el-input
          v-model="queryParams.fixedFemale"
          placeholder="请输入固定女生收费"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="女生优惠价格5" prop="femaleDiscountPrice">
        <el-input
          v-model="queryParams.femaleDiscountPrice"
          placeholder="请输入女生优惠价格5"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="每桶球数:12" prop="bucketBallNum">
        <el-input
          v-model="queryParams.bucketBallNum"
          placeholder="请输入每桶球数:12"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="每桶球价格:120" prop="bucketPerPrice">
        <el-input
          v-model="queryParams.bucketPerPrice"
          placeholder="请输入每桶球价格:120"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="场地数量默认1" prop="siteNum">
        <el-input
          v-model="queryParams.siteNum"
          placeholder="请输入场地数量默认1"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="每片场地每小时价格" prop="sitePerPrice">
        <el-input
          v-model="queryParams.sitePerPrice"
          placeholder="请输入每片场地每小时价格"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="时长：一般是两小时" prop="timeLength">
        <el-input
          v-model="queryParams.timeLength"
          placeholder="请输入时长：一般是两小时"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="额外每人：2元" prop="extraPerCost">
        <el-input
          v-model="queryParams.extraPerCost"
          placeholder="请输入额外每人：2元"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="额外固定：组一场球收50" prop="extraFixedCost">
        <el-input
          v-model="queryParams.extraFixedCost"
          placeholder="请输入额外固定：组一场球收50"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="租户编号" prop="tenantId">
        <el-input
          v-model="queryParams.tenantId"
          placeholder="请输入租户编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
       -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">清空</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['group:bg:add']"
        >建群
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['group:bg:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['group:bg:remove']"
        >删除
        </el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--            type="warning"-->
<!--            plain-->
<!--            icon="Download"-->
<!--            @click="handleExport"-->
<!--            v-hasPermi="['group:bg:export']"-->
<!--        >导出-->
<!--        </el-button>-->
<!--      </el-col>-->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="groupList" @selection-change="handleSelectionChange">
<!--      <el-table-column type="selection" width="55" align="center"/>-->
<!--      <el-table-column label="id" align="center" prop="id"></el-table-column>-->
      <el-table-column label="群名称" align="center" prop="groupName"/>
      <el-table-column label="分享码" align="center" width="100" prop="groupCode"/>
      <el-table-column label="群主" align="center" prop="groupOwner"/>
      <el-table-column label="用户名" align="center" prop="userGroupName"/>
      <el-table-column label="群角色" align="center" prop="adminType">
        <template #default="scope">
          <dict-tag :options="group_user_role" :value="scope.row.adminType"/>
        </template>
      </el-table-column>
      <el-table-column v-if="userStore.admin" label="用户id" align="center" prop="userId"/>
      <!--      <el-table-column label="是否注册" align="center" >-->
      <!--          <template #default="scope">-->
      <!--            <dict-tag :options="group_login_default" :value="scope.row.userId?1:0"/>-->
      <!--          </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="打水次数" align="center" class-name="small-padding ">
        <template #default="scope">
          <el-button link type="primary" icon="Link" v-hasPermi="['group:impRecord:listPage']"
                     @click="skipPage(scope.row,'/group/impRecord')">
            {{ scope.row.competitionNum }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="活动次数" align="center" class-name="small-padding ">
        <template #default="scope">
          <el-button link type="primary" icon="Link" v-hasPermi="['group:actRecord:listPage']"
                     @click="skipPage(scope.row,'/group/actRecord')">
            {{ scope.row.activityNum }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="收费方式" align="center" prop="collectType">
        <template #default="scope">
          <dict-tag :options="group_collect_type" :value="scope.row.collectType"/>
        </template>
      </el-table-column>
      <el-table-column label="固定男生收费" align="center" prop="fixedMale"/>
      <el-table-column label="固定女生收费" align="center" prop="fixedFemale"/>
      <el-table-column label="女生优惠价格(元)" align="center" prop="femaleDiscountPrice"/>
      <el-table-column label="每桶球/个" align="center" prop="bucketBallNum"/>
      <el-table-column label="每桶球价/元" align="center" prop="bucketPerPrice"/>
      <el-table-column label="场地数量、" align="center" prop="siteNum"/>
      <el-table-column label="/场/小时/元" align="center" prop="sitePerPrice"/>
      <el-table-column label="时长/H" align="center" prop="timeLength"/>
      <el-table-column label="额外每人/元" align="center" prop="extraPerCost"/>
      <el-table-column label="额外固定/次/元" align="center" prop="extraFixedCost"/>
      <el-table-column label="进群模式" align="center" prop="joinType">
        <template #default="scope">
          <dict-tag :options="group_join_type" :value="scope.row.joinType"/>
        </template>
      </el-table-column>
      <!--      <el-table-column label="租户编号" align="center" prop="tenantId" />-->
      <!--      <el-table-column label="备注" align="center" prop="remark"/>-->
      <el-table-column label="操作" align="center" class-name="small-padding " width="120">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['group:bg:update']" v-if="permitUpdate(scope.row.id)">
            修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-if="permitUpdate(scope.row.id)>1"
                     v-hasPermi="['group:bg:delete']">删除
          </el-button>
          <el-button link type="primary" icon="User" @click="skipPage(scope.row,'/group/guRef')"
                     v-hasPermi="['group:guRef:listPage']">成员
          </el-button>
          <el-button link type="primary" icon="Users" @click="skipPage(scope.row,'/group/level')"
                     v-hasPermi="['group:level:listPage']">等级规则
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改群对话框 -->
    <el-dialog :title="title" v-model="open" width="550px" append-to-body>
      <el-form ref="groupRef" :model="form" :rules="rules" label-width="110px">
        <!--        <el-form-item label="分享码" prop="groupCode">-->
        <!--          <el-input v-model="form.groupCode" placeholder="请输入分享码" />-->
        <!--        </el-form-item>-->
        <el-form-item label="群名称" prop="groupName">
          <el-input v-model="form.groupName" placeholder="请输入群名称"/>
        </el-form-item>
        <el-form-item label="收费模式" prop="collectType">
          <el-radio-group v-model.number="form.collectType">
            <el-radio
                v-for="dict in group_collect_type"
                :key="dict.value"
                :value="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="入群审核" prop="joinType">
          <el-radio-group v-model.number="form.joinType">
            <el-radio
                v-for="dict in group_join_type"
                :key="dict.value"
                :value="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <!--&lt;!&ndash;          <el-select v-model="form.collectType" placeholder="收费模式：0均摊，1固定；默认0" />&ndash;&gt;-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="打水次数" prop="competitionNum">-->
        <!--          <el-input v-model="form.competitionNum" placeholder="请输入打水次数" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="活动次数" prop="activityNum">-->
        <!--          <el-input v-model="form.activityNum" placeholder="请输入活动次数" />-->
        <el-form-item v-if="form.collectType === 1" label="固定男生收费" prop="fixedMale">
          <el-input v-model="form.fixedMale" placeholder="请输入固定男生收费"/>
        </el-form-item>
        <el-form-item v-if="form.collectType === 1" label="固定女生收费" prop="fixedFemale">
          <el-input v-model="form.fixedFemale" placeholder="请输入固定女生收费"/>
        </el-form-item>
        <el-form-item v-if="form.collectType === 0" label="女生优惠价格" prop="femaleDiscountPrice">
          <el-input v-model="form.femaleDiscountPrice" placeholder="请输入女生优惠价格5"/>
        </el-form-item>
        <el-form-item label="每桶球数" prop="bucketBallNum">
          <el-input v-model="form.bucketBallNum" placeholder="请输入每桶球数默认:12个"/>
        </el-form-item>
        <el-form-item label="每桶球价格" prop="bucketPerPrice">
          <el-input v-model="form.bucketPerPrice" placeholder="请输入每桶球价格:120"/>
        </el-form-item>
        <el-form-item label="场地数量" prop="siteNum">
          <el-input v-model="form.siteNum" placeholder="请输入场地数量默认2"/>
        </el-form-item>
        <el-form-item label="/场/小时/元" prop="sitePerPrice">
          <el-input v-model="form.sitePerPrice" placeholder="请输入每片场地每小时价格"/>
        </el-form-item>
        <el-form-item label="活动时长" prop="timeLength">
          <el-input v-model="form.timeLength" placeholder="请输入时长：一般是2小时"/>
        </el-form-item>
        <el-form-item label="额外每人" prop="extraPerCost">
          <el-input v-model="form.extraPerCost" placeholder="请输入额外每人：平均后每人加收，组织者辛苦费"/>
        </el-form-item>
        <el-form-item label="额外固定：" prop="extraFixedCost">
          <el-input v-model="form.extraFixedCost" placeholder="请输入额外固定：组一场球收50，组织者辛苦费"/>
        </el-form-item>
        <!--        <el-form-item label="是否删除" prop="deleted">-->
        <!--          <el-input v-model="form.deleted" placeholder="请输入是否删除" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="租户编号" prop="tenantId">-->
        <!--          <el-input v-model="form.tenantId" placeholder="请输入租户编号" />-->
        <!--        </el-form-item>-->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Group">
import * as groupServer from "@/api/group/group.js";
import {AES_Encrypt, encrypt} from "@/utils/jsencrypt.js";
import useUserStore from "@/store/modules/user.js";

const userStore = useUserStore();
const {proxy} = getCurrentInstance();
const {
  group_collect_type,
  group_user_role,
  group_join_type
} = proxy.useDict("group_collect_type", "group_user_role", "group_join_type");
const router = useRouter();
const groupList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const userGroups = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const groupPermitMap = reactive(new Map())

const data = reactive({
  form: {},
  queryParams: {
    orderByColumn: 'id',
    isAsc: 'desc',
    pageNum: 1,
    pageSize: 10,
    startTime: null,
    findTime: null,
    endTime: null,
    groupCode: null,
    groupName: null,
    competitionNum: null,
    activityNum: null,
    collectType: undefined,
    fixedMale: null,
    fixedFemale: null,
    femaleDiscountPrice: undefined,
    bucketBallNum: undefined,
    bucketPerPrice: undefined,
    siteNum: undefined,
    sitePerPrice: null,
    timeLength: undefined,
    extraPerCost: null,
    extraFixedCost: null,
    joinType: null,
    tenantId: null,
  },
  rules: {
    // groupCode: [
    //   { required: true, message: "分享码不能为空", trigger: "blur" }
    // ],
    groupName: [
      {required: true, message: "群名称不能为空", trigger: "blur"}
    ],
    // competitionNum: [
    //   { required: true, message: "打水次数不能为空", trigger: "blur" }
    // ],
    // activityNum: [
    //   { required: true, message: "活动次数不能为空", trigger: "blur" }
    // ],
    collectType: [
      {required: true, message: "收费方式：0均摊，1固定不能为空", trigger: "change"}
    ],
    fixedMale: [
      {required: false, message: "固定男生收费不能为空", trigger: "blur"}
    ],
    fixedFemale: [
      {required: false, message: "固定女生收费不能为空", trigger: "blur"}
    ],
    femaleDiscountPrice: [
      {required: false, message: "女生优惠价格5不能为空", trigger: "blur"}
    ],
    bucketBallNum: [
      {required: false, message: "每桶球数:12不能为空", trigger: "blur"}
    ],
    siteNum: [
      {required: false, message: "场地数量默认1不能为空", trigger: "blur"}
    ],
    timeLength: [
      {required: false, message: "时长：一般是两小时不能为空", trigger: "blur"}
    ],
    extraPerCost: [
      {required: false, message: "额外每人：2元不能为空", trigger: "blur"}
    ],
    extraFixedCost: [
      {required: false, message: "额外固定：组一场球收50不能为空", trigger: "blur"}
    ],
    joinType: [
      {required: false, message: "进群类型：0管理确认，1自动不能为空", trigger: "change"}
    ],
    createTime: [
      {required: false, message: "创建时间不能为空", trigger: "blur"}
    ],
    updateTime: [
      {required: false, message: "更新时间不能为空", trigger: "blur"}
    ],
    deleted: [
      {required: false, message: "是否删除不能为空", trigger: "blur"}
    ],
    tenantId: [
      {required: false, message: "租户编号不能为空", trigger: "blur"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);
const start = (() => {
  groupServer.callFindList(null).then(res => {
    userGroups.value = res.data
    userGroups.value.forEach(item => {
      groupPermitMap.set(item.id, item.adminType)
    })
  })
})
start()
function permitUpdate(groupId) {
  //console.log("-----------",groupId);
  return groupPermitMap.get(groupId)
}
/** 查询群列表 */
function getList() {
  loading.value = true;
  if (queryParams.value.findTime) {
    queryParams.value.endTime = queryParams.value.findTime[1]
    queryParams.value.startTime = queryParams.value.findTime[0]
  }
  groupServer.listGroup(queryParams.value).then(response => {
    groupList.value = response.data.list;
    total.value = response.data.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

function skipPage(row, path) {
  router.push({path: path, query: {groupId: AES_Encrypt(row.id)}});
}

// 表单清空
function reset() {
  form.value = {
    startTime: null,
    findTime: null,
    endTime: null,
    id: null,
    groupCode: null,
    groupName: null,
    competitionNum: null,
    activityNum: null,
    collectType: 0,
    fixedMale: null,
    fixedFemale: null,
    femaleDiscountPrice: null,
    bucketBallNum: 12,
    bucketPerPrice: null,
    siteNum: 2,
    sitePerPrice: null,
    timeLength: 2,
    extraPerCost: null,
    extraFixedCost: null,
    joinType: 0,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    deleted: null,
    tenantId: null,
    remark: null
  };
  proxy.resetForm("groupRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 清空按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.startTime = null;
  queryParams.value.findTime = null;
  queryParams.value.endTime = null;
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加群";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value[0]
  groupServer.getGroup({id: _id}).then(response => {
    form.value = response.data;
    // form.value.joinType+= ""
    // form.value.collectType+= ""
    open.value = true;
    title.value = "修改群";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["groupRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        groupServer.updateGroup(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        groupServer.addGroup(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id ? [row.id] : ids.value;
  proxy.$modal.confirm('是否确认删除群编号为"' + _ids + '"的数据项？').then(function () {
    return groupServer.delGroup({delIds: _ids});
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}


/** 导出按钮操作 */
function handleExport() {
  proxy.download('group/group/export', {
    ...queryParams.value
  }, `group_${new Date().getTime()}.xlsx`)
}

getList();
</script>
